package com.ktdaddy.service.impl;

import com.ktdaddy.enums.WhaleErrorCode;
import com.ktdaddy.exception.BusinessRuntimeException;
import com.ktdaddy.manager.RoleManager;
import com.ktdaddy.mapper.KernelRoleRelMapper;
import com.ktdaddy.mapper.RoleMapper;
import com.ktdaddy.pojo.KernelRoleRel;
import com.ktdaddy.pojo.Role;
import com.ktdaddy.request.CreateRoleReq;
import com.ktdaddy.request.QueryAllRoleReq;
import com.ktdaddy.request.RoleQueryReq;
import com.ktdaddy.request.RoleReq;
import com.ktdaddy.request.UpdateRoleReq;
import com.ktdaddy.service.RoleService;
import com.ktdaddy.utils.PageResult;
import com.ktdaddy.vo.RoleInfoVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author kdaddy@163.com
 * @date 2021/4/27 22:51
 */
@Service
public class RoleServiceImpl implements RoleService {

    private static final Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Resource
    private KernelRoleRelMapper kernelRoleRelMapper;

    @Resource
    private RoleManager roleManager;


    @Override
    public Set<String> loadByKernelName(String kernelName) {
        Set<String> roleCodeResult = new HashSet<>();

        Example example = new Example(KernelRoleRel.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("kernelName", kernelName);

        List<KernelRoleRel> result =  kernelRoleRelMapper.selectByExample(example);
        if(result.isEmpty()){
            return roleCodeResult;
        }
        roleCodeResult = result.stream().map(KernelRoleRel::getRoleCode).collect(Collectors.toSet());
        return roleCodeResult;
    }

    @Override
    public PageResult getRoleListByPage(RoleQueryReq roleQueryReq) {
        return  roleManager.getRoleListByPage(roleQueryReq);
    }

    @Override
    public boolean createRole(CreateRoleReq createRoleReq) {
        logger.info("roleService,createRole->{}",createRoleReq);
        //查询当前角色名是否已经存在，如果存在则不允许创建
        roleParamCheck(createRoleReq);

        //创建角色并且保存角色权限关系
        roleManager.saveRoleAndBuildPermission(createRoleReq);
        return true;
    }

    @Override
    public void deleteRole(Integer id) {
        roleManager.deleteRoleById(id);
    }

    @Override
    public boolean updateRole(UpdateRoleReq updateRoleReq) {
        logger.info("roleService,updateRole->{}",updateRoleReq);
        updateRoleParamCheck(updateRoleReq);

        //更新角色并且重置角色权限关系
        roleManager.updateRoleAndResetPermission(updateRoleReq);
        return true;
    }

    @Override
    public boolean setRoleStatus(Integer id, Integer status) {
        return roleManager.setRoleStatus(id,status);
    }

    @Override
    public List<RoleInfoVO> getAllRoleList(QueryAllRoleReq queryAllRoleReq) {
        List<RoleInfoVO> roleInfoVOList = roleManager.queryList(queryAllRoleReq.getRoleName(),queryAllRoleReq.getStatus());
        return roleInfoVOList;
    }

    private void updateRoleParamCheck(UpdateRoleReq updateRoleReq) {
        Role role = roleManager.getById(updateRoleReq.getId());
        if(Objects.isNull(role)){
            throw new BusinessRuntimeException(WhaleErrorCode.ROLE_NOT_EXIST);
        }
        if(!updateRoleReq.getRoleCode().equals(role.getRoleCode())){
            Role roleByCode = roleManager.findRoleByCode(updateRoleReq.getRoleCode());
            if(!Objects.isNull(roleByCode)){
                throw new BusinessRuntimeException(WhaleErrorCode.ROLE_CODE_EXIST);
            }
        }

        if(!updateRoleReq.getRoleName().equals(role.getRoleName())){
            //根据角色名称查询角色是否存在
            Role roleByName = roleManager.findRoleByName(updateRoleReq.getRoleName());
            if(!Objects.isNull(roleByName)){
                throw new BusinessRuntimeException(WhaleErrorCode.ROLE_NAME_EXIST);
            }
        }
    }

    /**
     * @param roleReq
     */
    private void roleParamCheck(RoleReq roleReq) {
        //根据角色名称查询角色是否存在
        Role roleByName = roleManager.findRoleByName(roleReq.getRoleName());
        //根据角色编号查询角色是否存在
        Role roleByCode = roleManager.findRoleByCode(roleReq.getRoleCode());
        if(!Objects.isNull(roleByCode)){
            throw new BusinessRuntimeException(WhaleErrorCode.ROLE_CODE_EXIST);
        }
        if(!Objects.isNull(roleByName)){
            throw new BusinessRuntimeException(WhaleErrorCode.ROLE_NAME_EXIST);
        }
    }
}
